class Robot {
  constructor(llm) {
    this.llm = llm;
  }

  async chat(userInput) {
    throw new Error("Not implemented");
  }

  async streamChat(userInput) {
    throw new Error("Not implemented");
  }
}

class RolePlayBot extends Robot {
  constructor({
    llm,
    characterName,
    characterDesc,
    personalityTraits = [],
    dialogueExamples = [],
    initialDialogue = [],
  }) {
    super(llm);

    if (!characterDesc) {
      throw new Error("角色描述不能为空");
    }

    this.characterName = characterName;
    this.messageHistory = [];

    // 构建系统提示
    const systemParts = [
      "## 角色设定",
      characterDesc,
      "## 核心行为准则",
      "- 始终保持角色设定，绝不脱离身份",
      "- 使用符合角色背景的语言风格",
    ];

    if (personalityTraits.length > 0) {
      systemParts.push("\n## 性格特征：", personalityTraits.join(", "));
    }

    if (dialogueExamples.length > 0) {
      const examplesStr = dialogueExamples
        .map(([q, a]) => `用户：${q}\n${this.characterName}：${a}`)
        .join("\n");
      systemParts.push("\n## 对话示例：", examplesStr);
    }

    this.systemTemplate =
      systemParts.join("\n") + "\n\n当前对话历史：\n{history}";

    // 添加初始对话
    if (initialDialogue.length > 0) {
      initialDialogue.forEach(([userInput, botResponse]) => {
        this.messageHistory.push(
          { role: "user", content: userInput },
          { role: "assistant", content: botResponse }
        );
      });
    }
  }

  _formatHistory() {
    return this.messageHistory
      .slice(-10) // 保留最近的10条消息
      .map(
        (msg) =>
          `${msg.role === "user" ? "用户" : this.characterName}：${msg.content}`
      )
      .join("\n");
  }

  async chat(userInput) {
    const messages = [
      {
        role: "system",
        content: this.systemTemplate.replace(
          "{history}",
          this._formatHistory()
        ),
      },
      { role: "user", content: userInput },
    ];

    const response = await this.llm.chat.completions.create({
      messages,
      model: "Pro/deepseek-ai/DeepSeek-V3",
      stream: false,
    });

    const botResponse = response.choices[0].message.content;

    this.messageHistory.push(
      { role: "user", content: userInput },
      { role: "assistant", content: botResponse }
    );

    return { rsp: botResponse.trim() };
  }

  async *streamChat(userInput) {
    const messages = [
      {
        role: "system",
        content: this.systemTemplate.replace(
          "{history}",
          this._formatHistory()
        ),
      },
      { role: "user", content: userInput },
    ];

    const stream = await this.llm.chat.completions.create({
      messages,
      model: "Pro/deepseek-ai/DeepSeek-V3",
      stream: true,
    });

    let fullResponse = "";

    for await (const chunk of stream) {
      const content = chunk.choices[0]?.delta?.content || "";
      fullResponse += content;
      yield { rsp: fullResponse };
    }

    this.messageHistory.push(
      { role: "user", content: userInput },
      { role: "assistant", content: fullResponse }
    );
  }

  getMemoryHistory() {
    const history = [];
    for (let i = 0; i < this.messageHistory.length; i += 2) {
      if (i + 1 < this.messageHistory.length) {
        history.push([
          this.messageHistory[i].content,
          this.messageHistory[i + 1].content,
        ]);
      }
    }
    return history;
  }
}

export { RolePlayBot };
